package com.deram.ctin.rest.web.controller.common;

import com.deram.ctin.common.utils.TemplateUtils;
import com.deram.ctin.common.utils.ValidateUtils;
import com.deram.ctin.dependencies.rest.base.BaseController;
import com.deram.ctin.serv.system.api.SystemTemplateApi;
import com.deram.ctin.serv.system.consts.SystemTemplateConsts;
import com.deram.ctin.serv.system.entity.SystemTemplate;
import com.deram.ctin.serv.third.api.CaptchaApi;
import com.deram.ctin.serv.third.api.SmsApi;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api(tags = {"common - 短信接口"})
@RestController
@RequestMapping("/common/captcha")
public class CommonCaptchaController extends BaseController {

    @Autowired
    private CaptchaApi captchaApi;

    @Autowired
    private SystemTemplateApi systemTemplateApi;

    @Autowired
    private SmsApi smsApi;

    @ApiOperation(value = "发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, paramType = "form")
    })
    @PostMapping("/sendSms")
    public void sendSms(String mobile) {
        ValidateUtils.isMobile(mobile);
        // 生成验证码
        String captcha = captchaApi.create(mobile);
        // 生成短信内容
        SystemTemplate template = systemTemplateApi.find(SystemTemplateConsts.SYS_CAPTCHA);
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("captcha", captcha);
        String content = TemplateUtils.createContent(template.getContent(), paramMap);
        // 发送短信
        smsApi.send(mobile, content);
    }
}
